package com.example.labapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.strictmode.CredentialProtectedWhileLockedViolation;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class registerAct extends Activity {
    private Spinner spinSubCollege;
    private Spinner spinClass;
    private Button btnRegister;
    private Button btnCanel;
    private ArrayList<String> arrSubCollege=new ArrayList<String>();
    private ArrayList<ArrayList<String>> arrClassList=new ArrayList<>();
    private EditText txtUserName;
    private EditText txtPasswd;
    private EditText txtStdID;
    private AlertDialog LoadingDlg=null;
    private Handler getDataHander=new Handler();
    ArrayAdapter<String> spinSubCollegeAdapter=null;
    private class UserInf
    {
        public String UserName;
        public String Passwd;
        public long StdID;
        public String SubCollege;
        public String StdClass;
    };
    UserInf userInf_=new UserInf();
    Connection DBconn=null;

    private AfterThread callbackAfer=(ErrorInf res)->{   //设置回调函数
        Looper.prepare();  //事件循环
        LoadingDlg.cancel();
        if(res.status)
        {
            Toast.makeText(registerAct.this,"注册成功",Toast.LENGTH_SHORT).show();
            registerAct.this.finish();
        }
        else
        {
            AlertDialog.Builder dlgBuilder=new AlertDialog.Builder(registerAct.this);
            dlgBuilder.setTitle("错误");
            dlgBuilder.setMessage("注册失败\n"+res.errStr);
            LoadingDlg=null;
            LoadingDlg=dlgBuilder.create();
            LoadingDlg.show();
        }
        Looper.loop();  //启动事件循环
    };
    private void commitInf()
    {
        AlertDialog.Builder dlgBuilder=new AlertDialog.Builder(registerAct.this);
        dlgBuilder.setTitle("处理中");
        dlgBuilder.setMessage("正在注册中,等待服务器响应");
        dlgBuilder.setCancelable(false);  //点击空白处不返回
        LoadingDlg=dlgBuilder.create();
        LoadingDlg.show();

        new Thread(new Runnable() {
            @Override
            public void run() {
                ErrorInf resData=new ErrorInf();  //返回一个结构出去
                try {
                    if(DBconn==null)
                    {
                        Class.forName("org.mariadb.jdbc.Driver");
                        DBconn = DriverManager.getConnection("jdbc:mariadb://124.222.159.110:3306/laboratory_APP?characterEncoding=utf-8/","labApp","3A9PvxE");
                    }
                    Statement stmt=DBconn.createStatement();
                    stmt.execute("INSERT INTO StudUser (StdID,StdName,StdSubCollege,StdClass,StdPasswd) VALUES ("+userInf_.StdID+",'"+userInf_.UserName+"','"+userInf_.SubCollege+"','"+userInf_.StdClass+"','"+userInf_.Passwd+"');");
                    stmt.execute(String.format("INSERT INTO examAnswerNum (stdID) VALUES (%s);",userInf_.StdID));
                } catch (SQLException | ClassNotFoundException throwables) {
                    throwables.printStackTrace();
                    resData.errStr=throwables.getMessage();
                    resData.errCode=-1;
                    resData.status=false;
                    callbackAfer.callback(resData);
                    return;
                }
                resData.status=true;
                callbackAfer.callback(resData);
            }
        }).start();
    }

    private void getInf()
    {
        AlertDialog.Builder dlgBuilder=new AlertDialog.Builder(registerAct.this);
        dlgBuilder.setTitle("处理中");
        dlgBuilder.setMessage("正在从服务器中获取数据");
        dlgBuilder.setCancelable(false);  //点击空白处不返回
        LoadingDlg=dlgBuilder.create();
        LoadingDlg.show();

        new Thread(new Runnable() {
            @Override
            public void run() {

                ErrorInf resData=new ErrorInf();  //返回一个结构出去
                try {
                    if(DBconn==null)
                    {
                        Class.forName("org.mariadb.jdbc.Driver");
                        DBconn = DriverManager.getConnection("jdbc:mariadb://124.222.159.110:3306/laboratory_APP?characterEncoding=utf-8/","labApp","3A9PvxE");
                    }
                    Statement stmt=DBconn.createStatement();
                    ResultSet subcollegeList= stmt.executeQuery("select distinct(subCollege) from classInf;");
                    while (subcollegeList.next())
                    {
                        String subcollegeName=subcollegeList.getString("subCollege");
                        arrSubCollege.add(subcollegeName);
                        ResultSet classList=stmt.executeQuery("select stdClass from classInf where subCollege='"+subcollegeName+"';");
                        ArrayList<String> arrClass=new ArrayList<>();
                        while (classList.next())
                        {
                            arrClass.add(classList.getString("stdClass"));
                        }
                        arrClassList.add(arrClass);
                    }
                } catch (SQLException | ClassNotFoundException throwables) {
                    throwables.printStackTrace();
                    resData.errStr=throwables.getMessage();
                    resData.errCode=-1;
                    resData.status=false;
                    getDataHander.post(new Runnable() {
                        //这一步需要与界面交互，用handler
                        @Override
                        public void run() {
                            LoadingDlg.cancel();
                            AlertDialog.Builder dlgBuilder=new AlertDialog.Builder(registerAct.this);
                            dlgBuilder.setTitle("错误");
                            dlgBuilder.setMessage("服务器连接失败\n"+resData.errStr);
                            dlgBuilder.setCancelable(false);
                            LoadingDlg=null;
                            LoadingDlg=dlgBuilder.create();
                            LoadingDlg.show();
                        }
                    });
                    return;
                }
                resData.status=true;
                getDataHander.post(new Runnable() {
                    @Override
                    public void run() {
                        LoadingDlg.cancel();
                        spinSubCollegeAdapter.notifyDataSetChanged();
                    }
                });
            }
        }).start();
    }

    private AlertDialog waitingDlg;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_act);
        initUI();
        getInf();
    }

    @Override
    protected void onDestroy()
    {

        super.onDestroy();
    }

    private void initUI()
    {
        spinClass=findViewById(R.id.spinClass);
        spinSubCollege=findViewById(R.id.spinSubCollege);
        btnCanel=findViewById(R.id.btnRegCancel);
        txtPasswd=findViewById(R.id.txtRegUserpasswd);
        txtUserName=findViewById(R.id.txtRegUsername);
        txtStdID=findViewById(R.id.txtRegStudID);
        btnRegister=findViewById(R.id.btnRegReg);
        btnCanel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent();
                setResult(RESULT_CANCELED,intent);
                registerAct.this.finish();
            }
        });
        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(txtStdID.getText().toString().length()!=9 || txtUserName.getText().toString().length()==0 || txtPasswd.getText().toString().length()==0)
                {
                    Toast.makeText(registerAct.this,"输入信息有误",Toast.LENGTH_SHORT).show();
                    return;
                }
                userInf_.UserName=txtUserName.getText().toString();
                userInf_.Passwd=txtPasswd.getText().toString();
                userInf_.StdID=Integer.valueOf(txtStdID.getText().toString());
                userInf_.StdClass=spinClass.getSelectedItem().toString();
                userInf_.SubCollege=spinSubCollege.getSelectedItem().toString();
                commitInf();
            }
        });

        spinSubCollegeAdapter=new ArrayAdapter<String>(registerAct.this, android.R.layout.simple_spinner_dropdown_item,arrSubCollege);
        spinSubCollege.setAdapter(spinSubCollegeAdapter);
        spinSubCollege.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                ArrayAdapter<String> adapter2=new ArrayAdapter<String>(registerAct.this, android.R.layout.simple_spinner_dropdown_item,arrClassList.get(i));
                spinClass.setAdapter(adapter2);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
    }
}
